<template>
  <div class="sku-con table-gl-w">
    <div class="search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal">
        <!-- <template #filterItemLeft>
          <a-radio-group type="button" @change="radioChange" v-model="searchValue.productType">
            <a-radio value="normal">普通产品</a-radio>
            <a-radio value="group">组合产品</a-radio>
          </a-radio-group>
        </template> -->
      </FilterTable>
    </div>

    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getList" fromLocation="产品SKU导出" :showExport="true" :seachData="searchValue" :exportInfo="exportInfo" :checkedList="selectIds">
        <template #headerLeft>
          <a-space>
            <a-dropdown @select="handleSelect($event, '导入')" class="dropdown" v-if="$authPass('product.sku.importProducts')">
              <a-button style="margin-left: 5px" class="gray-outline">导入 <icon-down /></a-button>
              <template #content>
                <a-doption value="1" v-if="$authPass('product.sku.importProducts')">导入SKU</a-doption>
                <a-doption value="2">导入SKU属性</a-doption>
                <!-- <a-doption value="2">导入SPU及关联的SKU</a-doption> -->
              </template>
            </a-dropdown>
            <!-- <a-dropdown @select="handleSelect" class="dropdown">
              <a-button style="margin-left: 5px" class="gray-outline">同步产品图片 <icon-down /></a-button>
              <template #content>
                <a-doption>同步全部产品</a-doption>
                <a-doption>同步选中产品</a-doption>
              </template>
            </a-dropdown> -->
            <a-dropdown @select="handleSelect" class="dropdown">
              <a-button style="margin-left: 5px" class="gray-outline">批量操作 <icon-down /></a-button>
              <template #content>
                <!-- <a-doption>批量更新产品图片</a-doption>
                <a-doption>更新持有人信息</a-doption>
                <a-doption>合并SKU到SPU中</a-doption> -->
                <!-- <a-doption @click="batchDel">删除SKU</a-doption> -->
                <a-doption @click.stop="syncReplenish">同步到智能补货</a-doption>
              </template>
            </a-dropdown>
            <div>
              <a-checkbox @change="isSelAll">全选</a-checkbox>
            </div>
            <div>
              已选：<span style="color: #1966ff">{{ selRows.length }}</span>
            </div>
            <a-button type="text" @click="selRows = false">清除已选</a-button>
          </a-space>
        </template>

        <template #headerRight> </template>

        <template #tableBody>
          <a-spin :loading="loading" :style="{ width: '100%', height: '100%' }">
            <a-scrollbar style="height: 100%; overflow: auto">
              <div v-if="tableData[0] && !loading" class="clearfix">
                <Item v-for="item of tableData" :item="item" @opreate="toOpearte($event, item)" />
              </div>
              <a-empty v-else />
            </a-scrollbar>
          </a-spin>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>

  <SkuDetail ref="SkuDetail" :detail="detail" @save="getList" :tableData="tableData" :categoryOptions="categoryOptions" />
  <ShowSkuDetail ref="showSkuDetail" :detail="detail" />
  <a-image-preview-group v-model:visible="visible" :srcList="srcList" />
  <ImportSku url="https://cdn2.selleroa.com/saas/file/138248165001346049.xlsx" uploadType="sku" v-if="showImportPairDialog" :isShow="showImportPairDialog" @closed="showImportPairDialog = false" @success="sizeChange(20)" />
  <CommonLogsDialog v-if="showLogDialog" api="pageProductLog" :id="detail.data.id" :isShow="showLogDialog" @closed="showLogDialog = false" />
  <ImportProperty v-if="showImportPairDialogPro" :isShow="showImportPairDialogPro" @closed="showImportPairDialogPro = false" @success="sizeChange(20)" />
</template>

<script lang="ts">
  import { reactive, ref, defineComponent, computed } from 'vue'
  import { getCategoryList, getProductSKUList, syncReplenishByProduct, getRelatedList, findDeptList, skuPageRelatedForCompanyVer } from '@/api/product'
  import { FilterTableItem, ExportInfo } from '@/types/components'
  import SearchItem from '@/components/searchItem.vue'
  import ShowSearchItem from '@/components/showSearchItem.vue'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import Item from './componetns/item.vue'
  import SkuDetail from './componetns/skuDetail.vue'
  import ShowSkuDetail from './componetns/showSkuDetail.vue'
  import { Modal, Message } from '@arco-design/web-vue'
  import dayjs from 'dayjs'
  import _, { values } from 'lodash-es'
  import { getOrganizesUser } from '@/api/system'
  import ImportSku from './componetns/importSku.vue'
  import CommonLogsDialog from '@/components/Log/logsDialog.vue'
  import ImportProperty from '../../productSetting/property/componetns/importProperty.vue'

  const dataOptions: any = [
    {
      label: 'SKU',
      value: 'skuList',
    },
    {
      label: 'SPU',
      value: 'spuList',
    },
    {
      label: '产品名称',
      value: 'skuNameList',
    },
  ]

  const rangeShortcuts: any = [
    {
      label: '今天',
      value: () => [dayjs(), dayjs().add(0, 'day')],
    },
    {
      label: '昨天',
      value: () => [dayjs().add(-1, 'day'), dayjs().add(-1, 'day')],
    },
    {
      label: '近三天',
      value: () => [dayjs(), dayjs().add(2, 'day')],
    },
    {
      label: '最近一周',
      value: () => [dayjs(), dayjs().add(6, 'day')],
    },
    {
      label: '最近一个月',
      value: () => [dayjs(), dayjs().add(1, 'month')],
    },
    {
      label: '最近三个月',
      value: () => [dayjs(), dayjs().add(3, 'month')],
    },
  ]
  // console.log(123);

  export default defineComponent({
    name: 'ProductSPU',
    components: { SearchItem, ShowSearchItem, TableWrap, Item, SkuDetail, ShowSkuDetail, FilterTable, ImportSku, CommonLogsDialog, ImportProperty },
    setup() {
      let searchValue: any = ref({})
      let showLogDialog = ref(false)
      let pageNation = reactive({ total: 30, pageSize: 20, pageNum: 1 })
      let visible = ref(false)
      let showImportPairDialog = ref(false)
      let showImportPairDialogPro = ref(false)
      let srcList = ref([])
      let selectIds: any = ref([])
      let loading = ref(false)
      let categoryOptions: any = ref()
      let showPopver = ref(false)
      const showTagList: any = ref([])
      const userList: any = ref([])
      const tableData = ref([])
      const SkuDetail = ref()
      const showSkuDetail = ref()
      const detail: any = ref({ type: '', data: {} })
      const importSku = ref()
      const search = (data: any) => {
        searchValue.value.skuList = ''
        searchValue.value.spuList = ''
        searchValue.value.skuNameList = ''
        searchValue.value[data.code] = data.value
        showPopver.value = false
      }
      const searchTime = () => {
        showPopver.value = false
      }

      let exportInfo: any = ref({
        title: '导出产品',
        type: 'single',
        supportAll: true,
        tabName: '导出产品',
        fieldList: [],
        supportTemplate: true,
        templateType: 'PRODUCT_SKU_UPLOAD',
        exportApi: 'exportProductSku',
        excelName: '产品导出',
      })

      const delTag = (data: any) => {}
      const handleSelect = (data: any, type: string) => {
        if (type == '添加SKU') {
          switch (data) {
            case '1':
              show('add')
              break
            case '2':
              break
            case '3':
              break
          }
        } else if (type == '导入') {
          if (data == 1) {
            showImportPairDialog.value = true
          } else if (data == 2) {
            showImportPairDialogPro.value = true
          }
        }
      }

      const filterItem: any = reactive([
        {
          type: 'sel_double',
          key: 'developerId',
          keyItems: [
            { label: '产品开发员', value: 'developerId' },
            { label: '销售员', value: 'salesId' },
          ],
          optionItems: [],
          keyWidth: '120',
          value: ref(),
          placeholder: '请选择',
          label: '产品开发员',
          width: 120,
          isMultiple: false,
        },
        {
          type: 'cascader',
          key: 'categoryIdList',
          optionItems: [],
          keyWidth: '120',
          value: ref(),
          placeholder: '商品分类',
          label: '类目',
          width: 200,
          isMultiple: true,
        },
        {
          type: 'select',
          key: 'purchaseDeptIdList',
          optionItems: [],
          keyWidth: '120',
          value: ref(),
          placeholder: '请选择采购部门',
          label: '采购部门',
          width: 160,
          isMultiple: true,
        },
        {
          type: 'input_keyword',
          key: 'skuList',
          keyItems: [
            { label: 'SKU', value: 'skuList' },
            { label: 'SPU', value: 'spuList' },
            { label: '产品名称', value: 'skuNameList' },
          ],
          keyWidth: '100',
          value: ref(),
          placeholder: '请输入',
          label: 'SKU',
          width: 160,
          isMultiple: true,
        },
        {
          type: 'keyword_date_range',
          key: 'gmtCreate',
          keyItems: [
            { label: '创建日期', value: 'gmtCreate' },
            { label: '更新时间', value: 'gmtWrite' },
          ],
          keyWidth: '110',
          value: ref(),
          placeholder: '请输入',
          label: '创建日期',
          width: 200,
        },
      ])

      const changePage = (val: number) => {
        pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        pageNation.pageNum = 1
        pageNation.pageSize = val
        getList()
      }
      const getCategory = async () => {
        const res: any = await getCategoryList()
        categoryOptions.value = res.data
        filterItem[1].optionItems = res.data
        // categoryOptions.value = res.data
      }

      const show = (type: string, data?: any) => {
        detail.value.type = type
        data ? (detail.value.data = data) : (detail.value.data = {})
        SkuDetail.value.visible = true
      }

      const toOpearte = (type: string, data: any) => {
        switch (type) {
          case 'showImg':
            showImg(data)
            break
          case 'detail':
            showDetail(data)
            break
          case 'edit':
            showEdit(data)
            break
          case 'log':
            detail.value.data = data
            showLogDialog.value = true
            break
          case 'del':
            showDel('single', data)
            break
        }
      }

      // 显示图片
      const showImg = (data: any) => {
        srcList.value = data.productPicList.map((e: any) => e.url)
        visible.value = true
      }
      // 查看详情
      const showDetail = (data: any) => {
        detail.value.data = data
        showSkuDetail.value.visible = true
      }
      // 编辑
      const showEdit = (data: any) => {
        show('edit', data)
      }

      const getList = async () => {
        let newValue: any = _.cloneDeep(searchValue.value)
        newValue.categoryIdList ? (newValue.categoryIdList = newValue.categoryIdList.split(',')) : (newValue.categoryIdList = [])
        newValue.skuList ? (newValue.skuList = newValue.skuList.split(',')) : (newValue.skuList = [])
        newValue.spuList ? (newValue.spuList = newValue.spuList.split(',')) : (newValue.spuList = [])
        newValue.skuNameList ? (newValue.skuNameList = newValue.skuNameList.split(',')) : (newValue.skuNameList = [])
        newValue.purchaseDeptIdList ? (newValue.purchaseDeptIdList = newValue.purchaseDeptIdList.split(',')) : (newValue.purchaseDeptIdList = [])
        // for (const key in newValue) {
        //   if (newValue[key] instanceof Array) {
        //     newValue[key] = newValue[key].join(',')
        //   }
        // }

        delete newValue.timeType
        delete newValue.userType
        loading.value = true
        let params = {
          ...newValue,
          productType: 'normal',
          pageNum: pageNation.pageNum,
          pageSize: pageNation.pageSize,
        }
        // const res: any = await getProductSKUList(params)
        const res: any = await skuPageRelatedForCompanyVer(params)
        if (res.code == 'SUCCESS') {
          pageNation.total = res.data.total
          tableData.value = res.data.records
        }
        loading.value = false
      }

      // 获取用户列表
      const getUSerList = async () => {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res: any = await getOrganizesUser(params)
        if (res.code == 'SUCCESS') {
          userList.value = res.data.records
          userList.value.map((e: any) => {
            e.label = e.userName
            e.value = e.id
            return e
          })
          filterItem[0].optionItems = userList.value
        }
      }
      // 同步智能补货
      const syncReplenish = async () => {
        if (!selRows.value.length) {
          Message.error('请选择产品')
          return
        }
        let ids = selRows.value.map((el: any) => el.id)
        const res: any = await syncReplenishByProduct({ productIds: ids })
        if (res) {
          Message.success('同步成功')
          getList()
        }
      }

      const searchByVal = (val: any) => {
        pageNation.pageNum = 1
        searchValue.value = {}
        searchValue.value = val

        if (searchValue.value.startDate) {
          searchValue.value.startDate = `${searchValue.value.startDate} 00:00:00`
          searchValue.value.endDate = `${searchValue.value.endDate} 23:59:59`
        }
        getList()
      }

      const radioChange = (val: any) => {
        pageNation.pageNum = 1
        getList()
      }
      const selRows: any = computed({
        set: (val) => {
          tableData.value.map((e: any) => (e.isSel = false))
        },
        get: () => {
          let arr = []
          arr = tableData.value.filter((e: any) => e.isSel)
          selectIds.value = []
          selectIds.value = arr.map((e: any) => e.id)
          return arr
        },
      })

      const batchDel = async () => {
        if (selRows.value.length <= 0) {
          return Message.error('请选择需要删除的数据')
        }
        showDel(
          'mul',
          tableData.value.filter((e: any) => e.isSel)
        )
      }

      // 删除
      const showDel = (type: string, data: any) => {
        let params: any = {
          idList: [],
        }

        if (type == 'single') {
          params.idList = new Array(data.id)
        } else {
          params.idList = data.map((e: any) => e.id)
        }

        Modal.error({
          title: '删除确认',
          content: '信息删除后无法恢复，确定要删除吗？',
          titleAlign: 'start',
          cancelText: '取消',
          hideCancel: false,
          onOk: async () => {
            const res: any = await delProductSPUList(params)
            if (res.code == 'SUCCESS') {
              Message.success('删除成功')
              getList()
              selRows.value = false
            }
          },
        })
      }

      // 获取属性列表

      const getPropertyList = async () => {
        let params = {
          pageSize: 999999,
        }
        const res: any = await getRelatedList(params)
        let arr: any = res?.data?.records || []
        let newArr: any = []
        arr.forEach((e: any) => {
          newArr.push({
            key: `propList.${e.code}`,
            name: e.name,
            keyType: '1',
            parentLevel: '属性',
          })
        })

        let baseObj = {
          group: '基础信息',
          columns: [
            { key: 'sku.sku', name: 'SKU', keyType: '1' },
            { key: 'sku.skuName', name: 'SKU名称', keyType: '1' },
            { key: 'sku.specValueList', name: '规格', keyType: '1' },
            { key: 'sku.productPicList', name: '产品图片', keyType: '2' },
            { key: 'sku.status', name: '产品状态', keyType: '1' },
            { key: 'sku.spu', name: 'SPU', keyType: '1' },
            { key: 'sku.weight', name: '重量', keyType: '1' },
            { key: 'sku.volume', name: '体积', keyType: '1' },
            { key: 'sku.developer', name: '开发员', keyType: '1' },
            { key: 'sku.salerList', name: '销售员', keyType: '1' },
            { key: 'sku.category', name: '产品类目', keyType: '1' },
            { key: 'sku.tagList', name: '标签', keyType: '1' },
            { key: 'sku.remark', name: '备注', keyType: '1' },
          ],
        }

        let propertyObj: any = {
          group: '属性信息',
          columns: newArr,
        }
        exportInfo.value.fieldList = [baseObj, propertyObj]
      }

      const isSelAll = (val: any) => {
        tableData.value.map((e: any) => {
          e.isSel = val
          return e
        })

        selectIds.value = []
        selectIds.value = tableData.value.filter((e: any) => e.isSel).map((e: any) => e.id)
      }

      const getDeptList = async () => {
        const res: any = await findDeptList()
        let arr = res?.data || []
        filterItem[2].optionItems = arr.map((e: any) => {
          e.label = e.deptName
          e.value = e.id
          return e
        })
      }

      getDeptList()

      getPropertyList()

      getUSerList()

      getList()
      getCategory()
      return {
        srcList,
        searchByVal,
        filterItem,
        loading,
        visible,
        getList,
        SkuDetail,
        showSkuDetail,
        searchValue,
        categoryOptions,
        dataOptions,
        search,
        searchTime,
        showPopver,
        rangeShortcuts,
        delTag,
        showTagList,
        handleSelect,
        pageNation,
        changePage,
        sizeChange,
        tableData,
        show,
        detail,
        toOpearte,
        radioChange,
        selRows,
        importSku,
        showImportPairDialog,
        showLogDialog,
        syncReplenish,
        batchDel,
        exportInfo,
        selectIds,
        isSelAll,
        showImportPairDialogPro,
      }
    },
  })
</script>

<style lang="less" scoped>
  .icon-r {
    .arco-icon {
      font-size: 16px;
      color: #000430;
    }
  }

  .arco-scrollbar {
    height: 100%;
    width: 100%;
  }

  .sku-con {
    height: calc(100vh - @menuAndTabHeight);
    width: 100%;
  }

  .body-con {
    // height: 100%;
    // width: 100%;
    padding: 5px;
    box-sizing: border-box;
    // margin-top: 10px;
    // overflow: auto;
    // display: flex;
    // justify-content: space-between;
    // flex-wrap: wrap;
  }

  .arco-dropdown-open .arco-icon-down {
    transform: rotate(180deg);
  }
</style>
